package com.xiaobao.campusLostFoundAfter.service;

import com.alibaba.fastjson.JSONObject;
import com.xiaobao.campusLostFoundAfter.utils.MD5Util;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class TencentMapService {

    @Value("${tencent.map.key}")
    private String apiKey;

    @Value("${tencent.map.secret}")
    private String secretKey;

    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    // 地址解析（文本转坐标）
    public Map<String, Object> geocoder(String address) throws IOException {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/";

        Map<String, String> params = new HashMap<>();
        params.put("address", address);
        return getStringObjectMap(url, params);
    }

    private Map<String, Object> getStringObjectMap(String url, Map<String, String> params) throws IOException {
        params.put("key", apiKey);

        String sign = generateSignature(url, params);
        params.put("sig", sign);

        String requestUrl = buildUrlWithParams(url, params);
        Request request = new Request.Builder()
                .url(requestUrl)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            String jsonData = null;
            if (response.body() != null) {
                jsonData = response.body().string();
            }
            return JSONObject.parseObject(jsonData);
        }
    }

    // 逆地址解析（坐标转地址）
    public Map<String, Object> reverseGeocoder(double latitude, double longitude) throws IOException {
        String url = "https://apis.map.qq.com/ws/geocoder/v1/";

        Map<String, String> params = new HashMap<>();
        params.put("location", latitude + "," + longitude);
        return getStringObjectMap(url, params);
    }

    // 生成签名
    private String generateSignature(String baseUrl, Map<String, String> params) {
        // 按字典序排序参数
        StringBuilder paramStr = new StringBuilder();
        params.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEach(entry -> paramStr.append(entry.getKey()).append("=").append(entry.getValue()).append("&"));

        // 移除最后一个&符号
        if (!paramStr.isEmpty()) {
            paramStr.deleteCharAt(paramStr.length() - 1);
        }

        // 拼接URL路径和参数
        String urlPath = baseUrl.substring(baseUrl.indexOf("/ws"));
        String stringToSign = urlPath + "?" + paramStr + secretKey;

        // 计算MD5签名
        return MD5Util.md5(stringToSign);
    }

    // 构建带参数的URL
    private String buildUrlWithParams(String baseUrl, Map<String, String> params) {
        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        urlBuilder.append("?");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            urlBuilder.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }

        // 移除最后一个&符号
        if (!urlBuilder.isEmpty() && urlBuilder.charAt(urlBuilder.length() - 1) == '&') {
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }

        return urlBuilder.toString();
    }
}